package com.example.commonlib.commonutil;

import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import Decoder.BASE64Decoder;

public class RsaUtils {
    private static final String TAG = "RsaUtils";

    private static final String DEFAULT_PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG9YGC1pERIucMSCIppAIVC1WX\n" +
            "NvLQ1XuyXqsEO2ncIDw/i5mZHx4QZXeh7XKLyFWxtzW4q4ZMxG5kulxY9zlveITN\n" +
            "sHfpH8WUm/Ef/uU1P+nyAJd/YRF31TX+cdk3lsWpm2Y5gGZEoNlACy/bSX4Jq/sQ\n" +
            "zH0P72buRMlNmuxDEQIDAQAB";

    private static final String DEFAULT_PRIVATE_KEY = "MIICXQIBAAKBgQCG9YGC1pERIucMSCIppAIVC1WXNvLQ1XuyXqsEO2ncIDw/i5mZ\n" +
            "Hx4QZXeh7XKLyFWxtzW4q4ZMxG5kulxY9zlveITNsHfpH8WUm/Ef/uU1P+nyAJd/\n" +
            "YRF31TX+cdk3lsWpm2Y5gGZEoNlACy/bSX4Jq/sQzH0P72buRMlNmuxDEQIDAQAB\n" +
            "AoGADehAQHIe2YFUPvndunpVm0McTPAPo5MW6nGYEid2i75n+olGwb2wKDLVdpf0\n" +
            "pRB25RexGdiAar+kkQ1eX+3uc6efVY7fohdBGt2UY8Any2De+k+JeJz7sze0GQ6S\n" +
            "zrj9+LZy8vjx9I9FPnRCdKFTqSD8IFtbMRwS1D4JcdqNwgUCQQCWv5LZQasHexQN\n" +
            "B1nO0tTqCy9MUkrZgK2vi3eLu04KPhBnpIgI0ywmkmZ9xd5FlwWVXZBXK0uKpOHM\n" +
            "3cH9TIWLAkEA5S/IWce5pBMcpgFmBOjCie6Pi2LFVicrigOR9pYJE/XfGCo+op0r\n" +
            "BbI5bbTbpy88axdGNhVDYy5ObUAvvivFUwJAZsEu1+hrLC44/KiGDvSnLOFy3BM7\n" +
            "8gZEXeQzGIwUJecoR31fPKS085XXRuQZHlZS9/1O5hwc4eSCBaMjGAWRAQJBANo6\n" +
            "+Yejyn0VRb48rqwWBsfYRQ7waf9zJN4yMBahHtvGzzvvXdzx0zmFT3HLOSykqd8/\n" +
            "NjfhX11dhog5Cj0G6MkCQQCTIRwtPUl7CkR29pvbRIrZPe9VogITYye+d2Dm1D6F\n" +
            "PJjvk+wEawb7iezK4ka9lyS85EhGGeoKH9eaHlr6Bfr2";

    public static final String KEY_ALGORITHM = "RSA";

    //签名算法
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    //获取公钥的key
    private static final String PUBLIC_KEY = "RSAPublicKey";

    //获取私钥的key
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    //RSA最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;

    //RSA最大解密密文大小
    private static final int MAX_DECRYPT_BLOCK = 128;

    //私钥
    private RSAPrivateKey privateKey;

    //公钥
    private RSAPublicKey publicKey;

    //字节数据转字符串专用集合
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 获取私钥
     * @return 当前的私钥对象
     */
    private RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * 获取公钥
     * @return 当前的公钥对象
     */
    private RSAPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * 随机生成密钥对
     */
    private void genKeyPair(){
        KeyPairGenerator keyPairGen= null;
        try {
            keyPairGen= KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyPairGen.initialize(1024, new SecureRandom());
        KeyPair keyPair= keyPairGen.generateKeyPair();
        this.privateKey= (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey= (RSAPublicKey) keyPair.getPublic();
    }

    /**
     * 从字符串中加载公钥
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    private void loadPublicKey(String publicKeyStr) throws Exception {
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer);
            this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (IOException e) {
            throw new Exception("公钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    private void loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr);
            PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (IOException e) {
            throw new Exception("私钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 公钥加密
     * @param publicKey 公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    private byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if(publicKey== null){
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher= null;
        try {
            KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(publicKey.getEncoded());
            PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(plainTextData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥解密
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    private byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
        if (privateKey== null){
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher= null;
        try {
            PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(
                    privateKey.getEncoded());
            KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privKey);
            return cipher.doFinal(cipherData);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }


    /**
     * 用RSA公钥解密
     *
     * @param
     *
     * @param data
     *            要解密的数据
     * @return 解密数据
     */
    private static byte[] decryptByRSA1(RSAPublicKey publicKey, byte[] data) {
        try {
            KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(publicKey.getEncoded());
            PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 使用RSA私钥加密数据
     *
     * @param
     *
     * @param data
     *            要加密的数据
     * @return 加密数据
     */
    private static byte[] encryptByRSA1(RSAPrivateKey privateKey, byte[] data){
        try {
            PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(
                    privateKey.getEncoded());
            KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, privKey);
            return cipher.doFinal(data);
        }
        catch (NoSuchAlgorithmException e) {
            System.out.println("无此加密算法");
            return null;
        } catch (InvalidKeyException e) {
            System.out.println("加密公钥非法,请检查");
            return null;
        } catch (IllegalBlockSizeException e) {
            System.out.println("明文长度非法");
            return null;
        } catch (BadPaddingException e) {
            System.out.println("明文数据已损坏");
            return null;
        } catch (Exception e){
            System.out.println("1111");
        }
        return null;
    }

    /**
     * 字节数据转十六进制字符串
     * @param data 输入数据
     * @return 十六进制内容
     */
    private static String byteArrayToString(byte[] data){
        StringBuilder stringBuilder= new StringBuilder();
        for (int i=0; i<data.length; i++){
            //取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]);
            //取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i<data.length-1){
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    private static String getSdCardPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    public static void test() throws Exception {
        RsaUtils rsaEncrypt= new RsaUtils();

        //加载公钥
        try {
            rsaEncrypt.loadPublicKey(DEFAULT_PUBLIC_KEY);
            System.out.println("加载公钥成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println("加载公钥失败");
        }
        //加载私钥
        try {
            rsaEncrypt.loadPrivateKey(DEFAULT_PRIVATE_KEY);
            System.out.println("加载私钥成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println("加载私钥失败");
        }
        //测试字符串
        String str = "服务器名服务器名;2017-12-23;192.168.1.100,192.168.111.251,192.168.111.251";

        System.out.println(System.currentTimeMillis());
        System.out.println("加密之前----------------:"+str);

        try {
            rsaEncrypt.testPublicPrivate(rsaEncrypt,str);
            rsaEncrypt.testPrivatePublic(rsaEncrypt,str);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    //公钥加密 私钥解密
    private void testPublicPrivate(RsaUtils rsaEncrypt, String encryptStr) throws Exception {

        byte[] bytes1 =  Base64.encode(encryptStr.getBytes("UTF-8"), Base64.DEFAULT);
        byte[] bytes = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), bytes1);
        String res = new String(Base64.encode(bytes, Base64.DEFAULT),"UTF-8");
        System.out.println(res);

        String path = getSdCardPath();
        FileOutputStream fos = new FileOutputStream(path+"/rsa_test/from_public");
        fos.write(bytes);
        fos.close();

        byte[] bytes3 = Base64.decode(res.getBytes("UTF-8"), Base64.DEFAULT);
        byte[] decrypt = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), bytes3);
        byte[] bytes2 = Base64.decode(decrypt, Base64.DEFAULT);
        System.out.println("私钥解码----------------:"+new String(bytes2,"UTF-8"));
    }

    // 私钥加密, 公钥解密
    private void testPrivatePublic(RsaUtils rsaEncrypt, String encryptStr)throws Exception {
        byte[] bytes1 =  Base64.encode(encryptStr.getBytes("UTF-8"), Base64.DEFAULT);
        byte[] bytes = RsaUtils.encryptByRSA1(rsaEncrypt.getPrivateKey(), bytes1);
        String res = new String(Base64.encode(bytes, Base64.DEFAULT),"UTF-8");
        System.out.println(res);

        String path = getSdCardPath();
        FileOutputStream fos = new FileOutputStream(path+"/rsa_test/from_private");
        fos.write(Base64.encode(bytes, Base64.DEFAULT),0, Base64.encode(bytes, Base64.DEFAULT).length);
        fos.close();

        byte[] bytes3 = Base64.decode(res.getBytes("UTF-8"), Base64.DEFAULT);

        byte[] bytes2 = rsaEncrypt.decryptByRSA1(rsaEncrypt.getPublicKey(), bytes3);
        byte[] bytes4 = Base64.decode(bytes2, Base64.DEFAULT);
        System.out.println("公钥解码----------------:"+new String(bytes4,"UTF-8"));
    }


    public RsaUtils()
    {
        //加载公钥
        try {
            loadPublicKey(DEFAULT_PUBLIC_KEY);
        } catch (Exception e) {
            Log.i(TAG, "加载公钥失败,"+e.getMessage());
        }
        //加载私钥
        try {
            loadPrivateKey(DEFAULT_PRIVATE_KEY);
            Log.i(TAG, "加载私钥成功");
        } catch (Exception e) {
            Log.i(TAG, "加载私钥失败,"+e.getMessage());
        }
    }

    /**
     * 公钥加密
     * @param encryptStr
     * @return
     */
    public String encodeData(String encryptStr)
    {
        String dst = "";
        try {
            byte[] bytes64 =  Base64.encode(encryptStr.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] bytes = encrypt(getPublicKey(), bytes64);
            dst = new String(Base64.encode(bytes, Base64.DEFAULT),"UTF-8");
            System.out.println(dst);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return dst;
    }

    /**
     * 公钥解密
     * @param res
     * @return
     */
    public String decodeData(String res)
    {
        String dstStr = "";
        try {
            byte[] bytes1 = Base64.decode(res.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] bytes2 = decryptByRSA1(getPublicKey(), bytes1);
            dstStr = new String(Base64.decode(bytes2, Base64.DEFAULT),"UTF-8");
            System.out.println(dstStr);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return dstStr;
    }


    public String encodeDataPrivate(String encryptStr)
    {
        String dst = "";
        try {
            byte[] bytes64 =  Base64.encode(encryptStr.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] bytes = encryptByRSA1(getPrivateKey(), bytes64);
            dst = new String(Base64.encode(bytes, Base64.DEFAULT),"UTF-8");
            System.out.println(dst);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return dst;
    }

    public String decodeDataPrivate(String res)
    {
        String dstStr = "";
        try {
            byte[] bytes1 = Base64.decode(res.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] bytes2 = decrypt(getPrivateKey(), bytes1);
            dstStr = new String(Base64.decode(bytes2, Base64.DEFAULT),"UTF-8");
            System.out.println(dstStr);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return dstStr;
    }
}
